package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.domain.StatementItem;
import cn.wolfcode.car.business.mapper.StatementItemMapper;
import cn.wolfcode.car.business.query.StatementItemQuery;
import cn.wolfcode.car.business.service.IStatementItemService;
import cn.wolfcode.car.business.service.IStatementService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import com.github.pagehelper.PageHelper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class StatementItemServiceImpl implements IStatementItemService {

    @Autowired
    private StatementItemMapper statementItemMapper;

    @Autowired
    private IStatementService statementService; // 使用service (服务层有Transactional 事务的处理) 而Mapper没有

    @Override
    public TablePageInfo<StatementItem> query(StatementItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<StatementItem>(statementItemMapper.selectForList(qo));
    }


    @Override
    public void save(StatementItem statementItem) {

        statementItemMapper.insert(statementItem);
    }

    @Override
    public StatementItem get(Long id) {
        return statementItemMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(StatementItem statementItem) {

        statementItemMapper.updateByPrimaryKey(statementItem);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            statementItemMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<StatementItem> list() {
        return statementItemMapper.selectAll();
    }

//    @Override
//    public List<StatementItem> queryByStatementItemId(Long statementId) {
//        return statementItemMapper.selectByStatementItemId(statementId);
//    }

    @Override
    @Transactional
    public void saveItems(List<StatementItem> items) {


        // 获取最后一条记录
        StatementItem statementItem = items.remove(items.size() - 1);
        // 获取前台传入的折扣金额
        BigDecimal discountPrice = statementItem.getItemPrice();
        // 合理性校验=>判断结算单的状态,是否为消费中
        Long statementId = statementItem.getStatementId();


        // 清除原先的数据
        statementItemMapper.deleteByStatementId(statementId);


        // 根据Id获取结算单对象
        Statement statement = statementService.get(statementId);
        if (Statement.STATUS_PAID.equals(statement.getStatus())) {
            // 已支付状态
            throw new BusinessException("已支付的结算单不能保存明细");
        }

        // 把明细项的集合删除掉



        // 计算整个明细的总金额和总数量
        BigDecimal totalAmount = new BigDecimal("0.0");
        BigDecimal totalQuantity = new BigDecimal("0");

        for (StatementItem item : items) {
            // 把每个结算单明细保存到数据库中
            statementItemMapper.insert(item);
            // 明细的单价*数量==>累加到总金额中
//            item.getItemPrice().multiply(new BigDecimal(item.getItemQuantity()));
            totalAmount = totalAmount.add(item.getItemPrice().multiply(new BigDecimal(item.getItemQuantity())));
            totalQuantity = totalQuantity.add(new BigDecimal(item.getItemQuantity()));
        }

        // 如果折扣金额大于总金额,属于非法的操作
        if (discountPrice.compareTo(totalAmount) > 0) {
            throw new BusinessException("折扣金额大于总金额,操作不合规范");
        }


        // 更新结算单信息
        statementService.updateAmount(statementId, totalAmount, totalQuantity, discountPrice);
    }


    @Override
    public void deleteByStatementId(Long id) {
        statementItemMapper.deleteByStatementId(id);
    }

    /**
     * 导出
     * @param response
     * @param statementId
     */
    @Override
    public void export(HttpServletResponse response, Long statementId) {
        List<StatementItem> statementItemList = statementItemMapper.queryStatementItemByStatementId(statementId);
        System.out.println(statementItemList);
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("结算单明细");
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("服务项名称");
        row.createCell(1).setCellValue("服务项价格");
        row.createCell(2).setCellValue("购买数量");
        StatementItem statementItem = null;
        for(int i=0;i<statementItemList.size();i++){
            Row row1 = sheet.createRow(i+1);
            statementItem = statementItemList.get(i);
            row1.createCell(0).setCellValue(statementItem.getItemName());
            row1.createCell(1).setCellValue(String.valueOf(statementItem.getItemPrice()));
            row1.createCell(2).setCellValue(statementItem.getItemQuantity());
        }

        try {
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.close();
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}
